#import "YQPMineInfoModel.h"

#import "MYMyUserInfoVC.h"
#import "YQImagePickerBaseVC.h"
#import "JJImagePicker.h"
#import "BRDatePickerView.h"
#import "MYMyUserInfoEditVC.h"

#import "MYNewsRankVC.h"
#import "MYNewsHotelSearchVC.h"
#import "MYNewsParentingSearchVC.h"
#import "MYNewsActionSearchVC.h"
#import "MYNewsHotActionSearchVC.h"
@interface MYMyUserInfoVC ()
@property (nonatomic, copy) NSArray * titleArr;
@property (nonatomic, copy) NSArray * subArr;
@property (nonatomic, strong) UIImage * userHeaderImage;

@property (nonatomic, strong) NSMutableDictionary * infoDict;
@property (nonatomic, copy) NSString * sexStr;
@property (nonatomic, copy) NSString * dateStr;

@property (strong, nonatomic) YQPMineInfoModel *model;

@property (nonatomic, copy) NSString *headImg;
@end

@implementation MYMyUserInfoVC


- (void)viewDidLoad {
    [super viewDidLoad];
    self.isNavShadow = YES;
    self.navigationItem.title = kYQLS(@"编辑个人资料");
    self.rightItemTitle = kYQLS(@"保存");
    self.titleArr = @[kYQLS(@"头像"),kYQLS(@"昵称"),kYQLS(@"姓名"),kYQLS(@"性别"),kYQLS(@"出生日期")];
    
    [self getUserInfoApi];
}
-(void)rightItemAction:(UIButton *)sender {
    NSString *sex;
    if ([self.sexStr isEqualToString:kYQLS(@"女")]) {
        sex = @"0";
    }else{
        sex = @"1";

    }
    if (sex.length == 0) {
        [QMUITips showInfo:kYQLS(@"请选择性别") inView:self.view];
        return;
    }
    NSMutableDictionary *dic = NSMutableDictionary.new;
    dic[@"userId"] = self.model.userId;
    dic[@"username"] = self.infoDict[@"1"];
    dic[@"birthday"] = self.dateStr;
    dic[@"gender"] = @(sex.intValue);
    if (self.headImg.length > 0) {
        dic[@"headImg"] = self.headImg;
    }
    dic[@"name"] = self.infoDict[@"2"];

    [YQPNetWorkingManager sendPostRequest:kPOST_COMPLETEINFORMATION_URL parameters:dic success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        [MBProgressHUD showSuccess:responseObject.msg];
        
        [self.navigationController popToRootViewControllerAnimated:YES];
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        
    }];
}

#pragma mark - 查询个人资料
- (void)getUserInfoApi
{
    [YQPNetWorkingManager sendGetRequest:kGET_QUERY_PROFILE_INFO_URL parameters:@{} success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        self.model = [YQPMineInfoModel mj_objectWithKeyValues:responseObject.data];
        self.subArr = @[self.model.username.length > 0?self.model.username:[NSString stringWithFormat:@"%@ %@",kYQLS(@"必填"),kYQLS(@"用于登录")],self.model.name.length > 0?self.model.name:kYQLS(@"必填"),self.model.gender.length > 0?(self.model.gender.intValue == 1?kYQLS(@"男"):kYQLS(@"女")):kYQLS(@"请选择"),self.model.birthday.length > 0?[[YQPInsureValidate timeInStr:self.model.birthday] substringToIndex:10]:kYQLS(@"请选择")];

        [self.listTableView reloadData];
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        
    }];
}
-(void)setupView {
    [super setupView];
    kYQREGISTERTABLEVIEWNIBCELL(@"MYMySetUserIconCell");
    kYQREGISTERTABLEVIEWNIBCELL(@"MYMySetTextCell");
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.self.titleArr.count;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        MYMySetUserIconCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYMySetUserIconCell"];
        cell.titleLb.text = self.titleArr[indexPath.row];
        if (self.model.headImg.length > 0) {
            [cell.userIcon sd_setImageWithURL:[NSURL URLWithString:self.model.headImg] placeholderImage:IMAGE_NAMED(@"")];
        }else{
            if (self.userHeaderImage) {
                cell.userIcon.image = self.userHeaderImage;
            }
        }
        return cell;
    }else{
        MYMySetTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYMySetTextCell"];
        
        cell.subLb.text = self.subArr[indexPath.row - 1];
        cell.titleLb.text = self.titleArr[indexPath.row];
        if (indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 3) {
            NSString *key = [NSString stringWithFormat:@"%zd",indexPath.row];
            NSString *text = self.infoDict[key];
            if ([text removeStringSpace].length > 0) {
                cell.subLb.text = text;
            }
            if(indexPath.row == 3){
                if (self.sexStr != nil) {
                    cell.subLb.text = self.sexStr;
                }
                
            }
        }else if(indexPath.row == 3) {
            if (self.sexStr != nil) {
                cell.subLb.text = self.sexStr;
            }
        }else if(indexPath.row == 4){
            if (self.dateStr != nil) {
                cell.subLb.text = self.dateStr;
            }else{
                cell.subLb.text = self.model.birthday;

            }
            
        }

        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 58;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row == 0) {
        [self setUserHeadIcon];
    } else if(indexPath.row == 1 || indexPath.row == 2){
        MYMyUserInfoEditVC *editVC = [[MYMyUserInfoEditVC alloc] init];
        editVC.indexPath = indexPath;
        editVC.textFieldblock = ^(NSString * _Nonnull text, NSIndexPath * _Nonnull indexPath) {
            NSString *key = [NSString stringWithFormat:@"%zd",indexPath.row];
            self.infoDict[key] = text;
            
            [self.listTableView reloadData];
        };
        kYQPUSH(editVC);
    }else if (indexPath.row == 3) {
        QMUIAlertController *sheet = [[QMUIAlertController alloc] initWithTitle:@"" message:@"" preferredStyle:(QMUIAlertControllerStyleActionSheet)];
        sheet.sheetCancelButtonAttributes = @{NSForegroundColorAttributeName:HexColor(0x999999),NSFontAttributeName:UIFontBoldMake(14),NSKernAttributeName:@(0)};
        sheet.sheetButtonAttributes = @{NSForegroundColorAttributeName:kAPPThemeColor,NSFontAttributeName:UIFontBoldMake(14),NSKernAttributeName:@(0)};
        [sheet addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"男") style:(QMUIAlertActionStyleDefault) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
            self.sexStr = kYQLS(@"男");
            self.infoDict[@(indexPath.row)] = self.sexStr;

            [self.listTableView reloadData];
        }]];
        [sheet addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"女") style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
             self.sexStr = kYQLS(@"女");
            self.infoDict[@(indexPath.row)] = self.sexStr;

            [self.listTableView reloadData];
        }]];
        [sheet showWithAnimated:YES];
    }else{
        [BRDatePickerView showDatePickerWithTitle:@"" dateType:(BRDatePickerModeYMD) defaultSelValue:@"1990-12-03" minDate:nil maxDate:[NSDate date] isAutoSelect:NO themeColor:nil resultBlock:^(NSString *selectValue) {
            self.dateStr = selectValue;
            self.infoDict[@(indexPath.row - 1)] = self.dateStr;
            [self.listTableView reloadData];
        } cancelBlock:^{
            
        }];
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001;
}
#pragma mark - UITableViewDelegate, UITableViewDataSource end

- (void)setUserHeadIcon {
    QMUIAlertController *sheet = [[QMUIAlertController alloc] initWithTitle:@"" message:@"" preferredStyle:(QMUIAlertControllerStyleActionSheet)];
    sheet.sheetCancelButtonAttributes = @{NSForegroundColorAttributeName:HexColor(0x999999),NSFontAttributeName:UIFontBoldMake(14),NSKernAttributeName:@(0)};
    sheet.sheetButtonAttributes = @{NSForegroundColorAttributeName:kAPPThemeColor,NSFontAttributeName:UIFontBoldMake(14),NSKernAttributeName:@(0)};
    
    [sheet addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"从相册选取") style:(QMUIAlertActionStyleDefault) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        // 从相册选择
        ws(self)
        JJImagePicker *picker = [JJImagePicker sharedInstance];
        [picker showImagePickerWithType:JJImagePickerTypePhoto InViewController:self didFinished:^(JJImagePicker *picker, UIImage *image) {
            [self uploadHeadImgApi:image];

            self.userHeaderImage = image;
            [weakself.listTableView reloadData];
            
        }];
    }]];
    
    [sheet addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"拍照") style:(QMUIAlertActionStyleDefault) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        
        // 拍照
        JJImagePicker *picker = [JJImagePicker sharedInstance];
        picker.customCropViewController = ^TOCropViewController *(UIImage *image) {
            if (picker.type == JJImagePickerTypePhoto) {
                //使用默认
                return nil;
            }
            TOCropViewController  *cropController = [[TOCropViewController alloc] initWithImage:image];
            //选择框可以按比例来手动调节
            cropController.aspectRatioLockEnabled = NO;
            //设置选择宽比例
            cropController.aspectRatioPreset = TOCropViewControllerAspectRatioPresetSquare;
            //显示选择框比例的按钮
            cropController.aspectRatioPickerButtonHidden = NO;
            //显示选择按钮
            cropController.rotateButtonsHidden = NO;
            //设置选择框可以手动移动
            cropController.cropView.cropBoxResizeEnabled = YES;
            return cropController;
        };
        [picker showImagePickerWithType:JJImagePickerTypeCamera InViewController:self didFinished:^(JJImagePicker *picker, UIImage *image) {
            
            self.userHeaderImage = image;
            [self.listTableView reloadData];
            [self uploadHeadImgApi:image];
        }];
        
    }]];
    
    [sheet addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"取消") style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        
    }]];
    
    [sheet showWithAnimated:YES];
}
#pragma mark - 上传用户头像
- (void)uploadHeadImgApi:(UIImage *)image
{
    MYMySetUserIconCell *cell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];

    [YQPImageUploader sendPOSTWithUrl:kPOST_FILE_UPLOAD_URL withLocalImage:image isNeedToken:YES parameters:@{} success:^(id  _Nullable responseObject) {
        self.headImg = responseObject[@"data"];
        [cell.userIcon sd_setImageWithURL:[NSURL URLWithString:self.headImg] placeholderImage:IMAGE_NAMED(@"")];
        [MBProgressHUD showMessage:kYQLS(@"上传成功")];
    } fail:^(NSError * _Nullable error) {

    }];
}

#pragma mark -- lazy
-(NSMutableDictionary *)infoDict {
    if (!_infoDict) {
        _infoDict = [NSMutableDictionary dictionary];
    }
    return _infoDict;
}
#pragma mark -- lazy
@end
